/*  
 * i-OSGi - Tunable Bundle Isolation for OSGi
 * Copyright (C) 2011  Sven Schulz
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
package org.iosgi.outpost.util.ipr;

import java.net.DatagramPacket;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.HashMap;
import java.util.Map;

/**
 * @author Sven Schulz
 */
public class IPRPacket {

	public static IPRPacket fromDatagram(final DatagramPacket packet)
			throws UnknownHostException {
		IPRPacket iprp = new IPRPacket();
		byte[] data = packet.getData();
		int pos = 0;
		while (pos < packet.getLength()) {
			byte[] mac = new byte[6];
			System.arraycopy(data, pos, mac, 0, 6);
			pos += 6;
			byte[] ip = new byte[4];
			System.arraycopy(data, pos, ip, 0, 4);
			pos += 4;
			iprp.add(new MacAddress(mac), InetAddress.getByAddress(ip));
		}
		return iprp;
	}

	private final Map<MacAddress, InetAddress> ipByMac;

	public IPRPacket() {
		ipByMac = new HashMap<MacAddress, InetAddress>();
	}

	public void add(MacAddress mac, InetAddress ip) {
		ipByMac.put(mac, ip);
	}

	public Map<MacAddress, InetAddress> getAll() {
		return ipByMac;
	}

	public DatagramPacket toDatagram() {
		byte[] data = new byte[ipByMac.size() * 10];
		int pos = 0;
		for (Map.Entry<MacAddress, InetAddress> e : ipByMac.entrySet()) {
			System.arraycopy(e.getKey().getRaw(), 0, data, pos, 6);
			pos += 6;
			System.arraycopy(e.getValue().getAddress(), 0, data, pos, 4);
			pos += 4;
		}
		DatagramPacket p = new DatagramPacket(data, data.length);
		return p;
	}

}